package com.cskaoyan.servlet;

import com.cskaoyan.bean.MarketStorage;
import com.cskaoyan.bean.common.BaseRespVo;
import com.cskaoyan.service.StorageService;
import com.cskaoyan.service.StorageServiceImpl;
import com.cskaoyan.util.JacksonUtil;
import lombok.SneakyThrows;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.InputStream;


/**
 * @author Yuye Wang
 * @date 2023/5/30 11:21
 * @description TODO
 */
@MultipartConfig
@WebServlet("/admin/storage/*")
public class AdminStorageServlet extends WdBaseServlet {
    private StorageService storageService = new StorageServiceImpl();

    @SneakyThrows
    private BaseRespVo create(HttpServletRequest request, HttpServletResponse response) {
        //获取参数
        request.setCharacterEncoding("utf-8");
        Part filePart = request.getPart("file");
        InputStream inputStream = filePart.getInputStream();
        long size = filePart.getSize();
        String contentType = filePart.getContentType();
        String fileName = filePart.getSubmittedFileName();

        //调用上传方法
        return storageService.create(inputStream, size, contentType, fileName);
    }

    @SneakyThrows
    private BaseRespVo list(HttpServletRequest request, HttpServletResponse response) {
        //获取参数
        String pageStr = request.getParameter("page");
        Integer page = Integer.parseInt(pageStr);

        String limitStr = request.getParameter("limit");
        Integer limit = Integer.parseInt(limitStr);

        String key = request.getParameter("key");

        String name = request.getParameter("name");

        String sort = request.getParameter("sort");

        String order = request.getParameter("order");

        //调用查询服务
        return storageService.list(page, limit, key, name, sort, order);
    }

    @SneakyThrows
    private BaseRespVo update(HttpServletRequest request, HttpServletResponse response) {
        //获取json对象
        String jsonStr = request.getReader().readLine();
        MarketStorage marketStorage = JacksonUtil.read(jsonStr, MarketStorage.class);

        //调用更新服务
        return storageService.update(marketStorage);
    }

    @SneakyThrows
    private BaseRespVo delete(HttpServletRequest request, HttpServletResponse response) {
        //获取json对象
        String jsonStr = request.getReader().readLine();
        MarketStorage marketStorage = JacksonUtil.read(jsonStr, MarketStorage.class);

        //调用删除服务
        return storageService.delete(marketStorage);
    }
}
